import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs';
// element-plus 按需加载 自动注册
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// 删除dist目录的函数
function deleteDist(distPath) {
  if (fs.existsSync(distPath)) {
    fs.rmSync(distPath, { recursive: true, force: true });
    fs.rmSync(`${distPath}.zip`, { recursive: true, force: true })
  }
}


export default defineConfig(({ command }) => {
  if (command === 'build') {
    // 在构建前执行删除dist目录的操作
    deleteDist('vue3');
  }
  return {
    plugins: [
      vue(),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        '@': '/src'
      }
    },
    server: {
      proxy: {
        '/api': {
          target: 'https://www.jialebixiaoxin.top/',
          changeOrigin: true,
          rewrite: path => {
            return path.replace(/^\/api/, '/api')
          }
        },
      }
    },
    // 改成相对路径
    base: './',
    // 打包设置
    build: {
      outDir: 'vue3',
      rollupOptions: {
        output: {
          entryFileNames: `assets/[name].js`, // 修改打包后的入口文件名称
          // 你还可以修改 chunk 文件名称和分割出的动态入口文件名称
          chunkFileNames: `assets/[name].js`,
          dynamicEntryFileNames: `assets/[name].js`,
        },
      },
    },
  }
})
